Author: RAMU MEDA
Date:
|
To
avoid conflicts with the services provided by container,, enterprise beans are
restricted from performing certain operations:
java.io
packageServerSocket
,
Socket
, or
the stream handler factory used by the URL
class·
Both
session and entity beans can access a database.
·
include
SQL calls in a session bean under the following circumstances:
·
The
application is relatively simple.
·
The
data returned by the SQL call will not be used by multiple clients.
·
The
data does not represent a business entity.
·
A
session bean represents a single client inside the J2EE server.
·
The
client accesses remote services by invoking the session bean's methods.
·
The
session bean performs work for its client, shielding the client from complexity
by executing business tasks inside the server.
·
As its
name suggests, a session bean is similar to an interactive session.
o
A
session bean is not shared-- it may have just one client, in the same way that
an interactive session may have just one user.
o
Like
an interactive session, a session bean is not persistent.
o
When
the client terminates, its session bean appears to terminate and is no longer
associated with the client.
·
Session
beans are powerful because they extend the reach of your clients into remote
servers-- yet they're easy to build. The following section shows you how to
construct a simple session bean.
The
session bean must meet these requirements:
SessionBean
interface.public
.abstract
or final
.ejbCreate
methods.public
constructor
with no parameters.finalize
method.EnterpriseBean
interface, which in turn extends the Serializable
interface. SessionBean
interface declares the ejbRemove
, ejbActivate
, ejbPassivate
, and setSessionContext
methods. Bean class
, but it must implement them
because they're declared in the SessionBean
interface. create
method on the
home object: ejbCreate
method Typically, an ejbCreate
method initializes the state
of the enterprise bean. ejbCreate
methods. The signatures of the methods meet the following requirements: public
.void
.static
or final
.javax.ejb.CreateException
and other exceptions that are specific to your application. The ejbCreate
method
usually throws a CreateException
if an input parameter is invalid. ·
The
primary purpose of a session bean is to run business tasks for the client.
·
The
client invokes business methods on the remote object reference that is returned
by the create
method.
·
From
the client's perspective, the business methods appear to run locally, but they
actually run remotely in the session bean.
·
The
signature of a business method must conform to these rules:
·
The
method name must not conflict with one defined by the EJB architecture. For
example, you cannot call a business method ejbCreate
or ejbActivate
.
·
The
access control modifier must be public
.
·
The
arguments and return types must be legal types for Java RMI.
·
The
modifier must not be static
or final
.
·
The
throws clause may include exceptions that you define for your application. The removeBook
method, for
example, throws the BookException
if the book is not in the cart.
·
To indicate
a system-level problem, such as the inability to connect to a database, a
business method should throw the javax.ejb.EJBException
.
When a business method throws an EJBException
,
the container wraps it in a RemoteException
,
which is caught by the client.
·
The
container will not wrap application exceptions.
·
Because EJBException
is a subclass of RuntimeException
,
you do not need to include it in the throws clause of the business method.
EJBHome
interface. create
methods that a client may invoke. create
method in the home interface
corresponds to an ejbCreate
method in the bean class. ejbCreate
and create
methods are
similar, but differ in important ways. The rules for defining the
signatures of the create
methods of a home interface follow: create
method must match those of its corresponding ejbCreate
method.create
method must be
valid RMI types.create
method returns the remote
interface type of the enterprise bean. (But an ejbCreate
method
returns void
.)create
method must
include the java.rmi.RemoteException
and the javax.ejb.CreateException
.· The remote interface, which extendsjavax.ejb.EJBObject
, defines the business methods that a client may invoke.
· The method definitions in a remote interface must follow these rules:
o Each method in the remote interface must match a method implemented in the enterprise bean class.
o The signatures of the methods in the remote interface must be identical to the signatures of the corresponding methods in the enterprise bean class.
o The arguments and return values must be valid RMI types.
o The throws clause must include thejava.rmi.RemoteException.
When
you specify the deployment descriptor of a session bean, you must choose
between two state management modes: stateful or stateless.
·
The
state is retained for the duration of the client-bean session.
·
When
the client removes the bean, the session ends and the state disappears.
·
This
transient nature of the state is not a problem, however, because when the
conversation between the client and the bean is over there is no need to retain
the state.
·
Because
stateless session beans can support multiple clients, they can offer
better scalability for applications that require large numbers of
clients.
·
Typically,
an application requires fewer stateless session beans than stateful
session beans to support the same number of clients.
·
At
times, the EJB container may write a stateful session bean out to secondary
storage. However, stateless session beans are never written out to secondary
storage. Therefore, stateless beans may offer better performance
than stateful beans.
·
The
home interface of a stateless session bean must have a single create
method with no
arguments.
·
The
session bean class must contain one ejbCreate
method, also without arguments. (The arguments are only needed by stateful
session beans, which use them to initialize their states.)
consider
using a stateful session bean if any of the following conditions are true:
·
The
bean's state must be initialized when it is created.
·
The
bean needs to hold information about the client across method invocations.
·
The client is an interactive application.
·
The
bean performs a task that is not tailored to the needs of a particular client.
For example, you might use a stateless session bean to fetch from a database a
commonly used set of data.
·
The
bean doesn't need to hold information about the client across method
invocations.
create
method.setSessionContext
and ejbCreate
methods in the session bean. The bean is now ready to have its business
methods invoked. ejbPassivate
method immediately before passivating it.ejbActivate
method.
remove
method and the EJB container calls the bean's ejbRemove
method. The
bean's instance is ready for garbage collection. create
and remove
methods in the client. All other methods are invoked by the EJB container.
The ejbCreate
method, for example, is inside the bean class, allowing you to perform
certain operations right after the bean is instantiated. For instance, you
may wish to connect to a database in the ejbCreate
method. FIGURE 3-2 Life Cycle of a Stateless Session Bean
isIdentical
method: bookCart = home.create("Bill Shakespeare");
videoCart = home.create("Lefty Lee");
. . .
if (bookCart.isIdentical(bookCart)) {
// true . . . }
if (bookCart.isIdentical(videoCart)) {
// false . . . }
· Because stateless session beans have the same object identity, theisIdentical
method always returns true when used to compare two such beans.
this
reference, to pass a reference to itself, to another bean because the
session bean is not a remote object.getEJBObject
method of the SessionContext
interface lookup
with the "java:comp/env"
parameter. Then it calls lookup
on the environment to get the values for the "Discount Level" ..
·
An
entity bean represents an entity kept in a persistent storage mechanism,
usually a database.
·
Inside
the J2EE server, this application would represent the business entity objects
with entity beans.
ejbCreate
method, for example, will issue the SQL insert
statement. You are responsible for
coding the insert
statement and any other necessary SQL calls. The
entity bean class meets the requirements of every entity bean:
EntityBean
interface.public
.abstract
or final
.ejbCreate
and ejbPostCreate
methods.finalize
method.EnterpriseBean
interface, which extends the Serializable
interface. EntityBean
interface declares a number of
methods, such as ejbActivate
and ejbLoad
,
which you must implement in your entity bean class. create
method, the EJB container invokes the corresponding ejbCreate
method. ejbCreate
method in an
entity bean performs the following tasks: ejbCreate
methodsejbCreate
method for
an entity bean, be sure to follow these rules: public
.final
or static
.throws
clause may include the javax.ejb.CreateException
and other exceptions that are specific to your application. ejbCreate
method usually throws a CreateException
if an
input parameter is invalid. ejbCreate
method cannnot create an
entity because another entity with the same primary key already exists,
it should throw a javax.ejb.DuplicateKeyException
(a subclass of CreateException
).CreateException
or a DuplicateKeyException
,
it should assume that the entity was not created. ejbCreate
method, the
bean can be located by a client program. ejbCreate
method, you
must write an ejbPostCreate
method in the entity bean class. ejbPostCreate
immediately after it calls ejbCreate
.
Unlike the ejbCreate
method, the ejbPostCreate
method can invoke the getPrimaryKey
and getEJBObject
methods of the EntityContext
interfaceejbPostCreate
methods will be empty. ejbPostCreate
must
meet the following requirements: ejbCreate
method.public
.final
or static
.void
.throws
clause may include the javax.ejb.CreateException
,
and other exceptions that are specific to your application. remove
method. ejbRemove
method, which deletes the entity state from the database. ejbRemove
method encounters a system
problem, it should throw the javax.ejb.EJBException
.
If it encounters an application error, it should throw a javax.ejb.RemoveException
.
ejbLoad
and ejbStore
methods. ejbLoad
method refreshes the instance
variables from the database, and the ejbStore
method writes the variables to the database. ejbLoad
and ejbStore
. ejbLoad
before the business method
executes. ejbStore
.ejbLoad
and ejbStore
, you do not
have to refresh and store the instance variables in your business
methods-- the container performs these functions for you. ejbLoad
and ejbStore
methods cannot locate an entity
in the underlying database, they should throw the javax.ejb.NoSuchEntityException
.
This exception is a subclass of EJBException
.
Because EJBException
is a subclass of RuntimeException
,
you do not have to include it in the throws clause. When NoSuchEntityException
is thrown, the EJB container wraps it in a RemoteException
before returning it to
the client. · The finder methods allow clients to locate entity beans.
· For every finder method available to a client, the entity bean class must implement a corresponding method that begins with the prefixejbFind
.
· The finder methods specific to your application, such asejbFindByLastName
andejbFindInRange
, are optional, but theejbFindByPrimaryKey
method is required. As its name infers, theejbFindByPrimaryKey
method accepts as an argument the primary key, which it uses to locate an entity bean.
· TheejbFindByPrimaryKey
method may look strange to you, because it uses aprimaryKey
for both the method argument and return value. However, remember that the client does not callejbFindByPrimaryKey
directly. It is the EJB container that calls theejbFindByPrimaryKey
method. The client invokes thefindByPrimaryKey
method, which is defined in the home interface.
· The following list summarizes the rules for the finder methods that you implement in an entity bean class with bean-managed persistence:
o TheejbFindByPrimaryKey
method must be implemented.
o A finder method name must start with the prefixejbFind
.
o The access control modifier must bepublic
.
o The method modifier cannot befinal
orstatic
.
o The arguments and return type must be legal types for Java RMI.
o The return type must be the primary key or a collection of primary keys.
o Thethrows
clause may include thejavax.ejb.FinderException
, and other exceptions that are specific to your application.
o If a finder method returns a single primary key, it should throw thejavax.ejb.ObjectNotFoundException
if the requested entity does not exist. TheObjectNotFoundException
is a subclass ofFinderException.
o If a finder method returns a collection of primary keys, it should throw aFinderException.
ejbCreate
or ejbActivate
.
public
.final
or static
.throws
clause may include the the
exceptions that you define for your application. The debit
method, for
example, throws the InsufficientBalanceException
.
To indicate a system-level problem, a business method should throw the javax.ejb.EJBException
.
create
methods in the home interface must conform to these requirements: ejbCreate
method in the enterprise bean class.throws
clause includes the exceptions
specified by the throws
clause of the corresponding ejbCreate
and ejbPostCreate
methods.throws
clause contains the java.rmi.RemoteException
and the javax.ejb.CreateExceptio
n.
·
Every
finder method in the home interface corresponds to a finder method in the
entity bean class.
·
The
name of a finder method in the home interface begins with find
, whereas the name of
one in the entity bean class begins with ejbFind
.
·
The
rules for defining the signatures of the finder methods of a home interface
follow:
o
The
number and types of arguments must match those of the corresponding method in
the entity bean class.
o
The
return type is the entity bean's remote interface type, or a collection of
those types.
o
The
exceptions in the throws
clause include those of the corresponding method in the entity bean class.
o
The throws
clause contains the javax.ejb.FinderException
and the javax.ejb.RemoteException
.
o The remote interface extendsjavax.ejb.EJBObject
and defines the business methods that a client may invoke.
o The requirements for the method definitions in a remote interface are the same for both session and entity beans:
o Each method in the remote interface must match a method in the enterprise bean class.
o The signatures of the methods in the remote interface must be identical to the signatures of the corresponding methods in the enterprise bean class.
o The arguments and return values must be valid RMI types.
o Thethrows
clause must includejava.rmi.RemoteException
ProductEJB
instance. ejbCreate
method
initializes the container-managed fields from the input parameters. ejbCreate
method
executes, the container inserts the container-manged fields into the
database. remove
method, the container calls the ejbRemove
method. ejbRemove
method
returns, the container deletes the row from the database.ejbRemove
method. When
the container needs to refresh the entity bean's state from the database, it
performs these steps:
ejbLoad
methodejbLoad
method is
empty. The entity bean may use the ejbLoad
method, however, to transform the values read from the database. For
example, the ejbLoad
method might uncompress text data so that it can be manipulated by the
business methods. When
the container needs to save the entity bean's state in the database, it
performs these steps:
ejbStore
methodejbLoad
method, the ejbStore
method is
typically empty. But if you need to transform container-managed fields
before the container stores them in the database, you should do so in the ejbStore
method. For
example, the ejbStore
method might compress text data before the container stores it in the
database. The
exceptions thrown by enterprise beans fall into two categories: system and application.
·
A system
exception indicates a problem with the services that
support an application.
o
Examples
of these problems include the following: a database connection cannot be
obtained, a SQL insert
fails because the database is full, a lookup
method cannot find the desired object.
o
If
your enterprise bean encounters a sytem-level problem, it should throw a javax.ejb.EJBException
. The
container will wrap the EJBException
in a RemoteException
,
which it passes back to the client.
o
Because the EJBException
is a subclass of the RuntimeException
, you do
not have to specify it in the throws clause of the method declaration.
o
If a system exception is thrown, the EJB
container might destroy the bean instance. Therefore, a system exception cannot
be handled by the bean's client program; it requires intervention by a system
administrator.
·
An
application exception signals an error in the business logic of an
enterprise bean.
o
There
are two types of application exceptions: customized and predefined.
o
A
customized exception is one that you've coded yourself, such as the InsufficentBalanceException
thrown by the debit
business method of the AccountEJB
example.
o
The javax.ejb
package includes
several predefined exceptions that are designed to handle common problems. For
example, an ejbCreate
method should throw a CreateException
to indicate an invalid input parameter.
o
When
an enterprise bean throws an application exception, the container does not wrap
it in another exception. The client should be able to handle any application
exception it receives.
o
If a
system exception occurs within a transaction, the EJB container rolls back the
transaction. However, if an application exception is thrown within a
transaction, the container does not roll back the transaction.
The following
table summarizes the exceptions of the javax.ejb
package. All of these exceptions are application exceptions, except for the NoSuchEntityException
and
the EJBException
,
which are system exceptions.
The
database row for the requested entity bean is cannot be found. |
||
ProductEJB
bean, for
example, you would specify a java.lang.String
as the primary key class.String
or some other class that belongs to the java
package. public
.public
.public
default
constructor.hashCode()
and equals(Object other)
methods.ejbCreate
method returns null. (With
bean-managed persistence, it returns an instance of the primary key
class.) ejbFindByPrimaryKey
method. · A client can fetch the primary key of an entity bean by invoking thegetPrimaryKey
method of theEJBObject
class: account.getPrimaryKey();
· The entity bean retrieves its own primary key by calling thegetPrimaryKey
method of the context.getPrimaryKey();
setEntityContext
method of the entity bean class. The setEntityContext
method passes the entity context to the bean. create
method, causing
the EJB container to call the ejbCreate
and ejbPostCreate
methods. On the second path, the EJB container invokes the ejbActivate
method.
While in the ready stage, an entity bean's business methods may be
invoked. remove
method, which
causes the EJB container to call the ejbRemove
method. Second, the EJB container may invoke the ejbPassivate
method. unsetEntityContext
method. FIGURE 4-1 Life Cycle of an Entity Bean
·
In the
pooled state, an instance is not associated with any particular EJB object
identity.
·
With
bean-managed persistence, when the EJB container moves an instance from the
pooled state to the ready state, it does not automatically set the primary key.
Therefore, the ejbCreate
and ejbActivate
methods must set the primary key.
·
If the
primary key is incorrect, the ejbLoad
and ejbStore
methods cannot synchronize the instance variables with the database.
·
In the
pooled state, the values of the instance variables are not needed. You can make
these instance variables eligible for garbage collection by setting them to
null in the ejbPasssivate
method.
isIdentical
method: Account accta, acctb;
. . .
if (accta.isIdentical(acctb))
System.out.println("identical");
Or, the client can fetch and compare the
primary keys of two entity beans:
String key1 = (String)accta.getPrimaryKey();
String key2 = (String)acctb.getPrimaryKey();
if (key1.compareTo(key2) == 0)
System.out.println("equal");
this
reference.
Instead, you must pass the entity bean's object reference by retrieve the object reference by calling getEJBObject
on the EntityContext
of an
entity bean. A
transaction attribute may have one of the following values:
TransactionRequiredException
.
RemoteException
.Table
6-1 summarizes the effects of the transaction attributes. Both the T1 and T2
transactions are controlled by the container. A T1 transaction is associated
with the client that calls a method in the enterprise bean. In most cases, the
client is another enterprise bean. A T2 transaction is started by the container
just before the method executes.
In the last
column, the word "none" means that the business method does not
execute within a transaction controlled by the container. However, the database
calls in such a business method might be controlled by the transaction manager
of the DBMS.
|
create
methods. Entity beans require transaction attributes for the business, create
, remove
, and finder
methods. setRollbackOnly
method of the EJBContext
interface, the bean method instructs the container to roll back the
transaction. If the bean throws an application exception,
the roll back is not automatic, but may be initiated by a call to setRollbackOnly
.
ejbLoad
method, which loads the instance variables from the database.) SessionSynchonization
interface. SessionSynchonization
interface, which is optional, allows you to synchronize the
instance variables with their corresponding values in the database. SessionSynchonization
methods-- afterBegin
,
beforeCompletion
,
and afterCompletion
--
at each of the main stages of a transaction. afterBegin
method informs the instance
that a new transaction has begun. The container invokes afterBegin
immediately
before it invokes the business method. The afterBegin
method is a good place to load
the instance variables from the database. beforeCompletion
method after the business method has finished, but just before the transaction
commits. The beforeCompletion
method is the last opportunity for the session bean to roll back the
transaction (by calling setRollbackOnly
).
If it hasn't already updated the database with the values of the instance
variables, the session bean may do so in the beforeCompletion
method. afterCompletion
method indicates that the
transaction has completed. It has a single boolean parameter, whose value
is true if the transaction was committed and false if it was rolled back.
If a rollback occurred, the session bean can refresh its instance
variables from the database in the afterCompletion
methodYou
should not invoke any method that might interfere with the transaction
boundaries set by the container. The list of prohibited methods follows:
commit
, setAutoCommit
,
and rollback
methods of java.sql.Connection
getUserTransaction
method of javax.ejb.EJBContext
javax.transaction.UserTransaction
You
may, however, use these methods to set boundaries in bean-managed transactions.
The following
pseudo-code illustrates the kind of fine-grained control you can obtain with
bean-managed transactions. By checking various conditions, the pseudo-code
decides whether to start and stop different transactions within the business
method.
begin transaction
...
update table-a
...
if (condition-x)
commit transaction
else if (condition-y)
update table-b
commit transaction
else
rollback transaction
begin transaction
update table-c
commit transaction
When
coding a bean-managed transaction, you must decide whether to use JDBC or JTA
transactions. The sections that follow discuss the techniques and merits of
both approaches.
commit
and rollback
methods of the javax.sql.Connection
interface. commit
,
rollback
,
or connect
statement. (This rule is generally true, but may vary with DBMS vendor.) The following code is from the WarehouseEJBexample,
a session bean that uses the Connection
interface's methods to delimit bean-managed transactions. The ship
method starts by
invoking setAutoCommit
on the Connection
object con
.
This invocation tells the DBMS not to automatically commit every SQL statement.
Next, the ship
method calls routines that update the order_item
and inventory
database tables. If the updates succeed, the transaction is committed. But if
an exception is thrown, the transaction is rolled back.
public void ship (String productId, String orderId, int quantity) {
try {
con.setAutoCommit(false);
updateOrderItem(productId, orderId);
updateInventory(productId, quantity);
con.commit();
} catch (Exception ex) {
try {
con.rollback();
throw new EJBException("Transaction failed: " +
ex.getMessage());
} catch (SQLException sqx) {
throw new EJBException("Rollback failed: " +
sqx.getMessage());
}
}
}
begin
,
commit
,
and rollback
methods of the UserTransaction
interface. UserTransaction
methods. The begin
and commit
invocations delimit the updates to the database. If the updates fail, the
code invokes the rollback
method and throws an EJBException
.
public void withdrawCash(double amount) {
UserTransaction ut = context.getUserTransaction();
try {
ut.begin();
updateChecking(amount);
machineBalance -= amount;
insertMachine(machineBalance);
ut.commit();
} catch (Exception ex) {
try {
ut.rollback();
} catch (SystemException syex) {
throw new EJBException
("Rollback failed: " + syex.getMessage());
}
throw new EJBException
("Transaction failed: " + ex.getMessage());
}
}
getRollbackOnly
and setRollbackOnly
methods of the EJBContext
interface. These methods should be used only in container-managed
transactions.getStatus
and rollback
methods of the UserTransaction
interface. The
decision tree in figure 6-2 shows the different approaches to transaction
management that you may take.
setRollbackOnly
method of the EJBContext
interface. commit
and rollback
methods of the Connection
interface. To demarcate JTA transactions, you invoke the begin
, commit
, and rollback
methods of
the UserTransaction
interface. FIGURE ;
Options in Specifying Transactions
transaction.timeout
property in the config/default.properties
file. For example, you would set the timeout value to 5 seconds as
follows: transaction.timeout=5 With this setting, if the transaction
has not completed within 5 seconds, the EJB container manager rolls it
back.
transaction.timeout=0
If the value is 0, the transaction will not time out.
transaction.timeout
property. For enterprise beans with bean-managed, JTA transactions, you
invoke the setTransactionTimeout
method of the UserTransaction
interface. setTransactionIsolation
method: Connection con; ... con.setTransactionIsolation(TRANSACTION_READ_UNCOMMITTED);In figure 6-3,
the client invokes a business method in Bean-A. The business method begins a
transaction, updates Database-X, updates Database-Y, and invokes a business
method in Bean-B. The second business method updates Database-Z and returns
control to the the business method in Bean-A, which commits the transaction.
All three database updates occur in the same transaction.
FIGURE 6-3 Updating Multiple Databases
In figure 6-4,
the client calls a business method in Bean-A, which begins a transaction and
updates Database-X. Then, Bean-A invokes a method in Bean-B, which resides in a
remote J2EE server. The method in Bean-B updates Database-Y. The transaction
managers of the J2EE servers ensure that both databases are updated in the same
transaction.
FIGURE 6-4 Updating Multiple Databases Across J2EE
Servers
·
You
declare the security attributes of an enterprise bean in with the Application
Deployment Tool.
·
This declarative
approach to security enforcement has two major advantages.
o
First,
you save time because you don't have to code and debug security
routines in your enterprise beans or their clients.
o
Second,
the administrator of the J2EE server can customize the security
attributes for a particular production environment at deployment time.
·
The
J2EE server enforces security at two levels: Authentication
and Authorization.
Authentication
·
Authentication is the process by which a user proves his
or her identity to a system.
·
The
J2EE server controls client access with a distributed authentication service.
·
This
service controls whether or not a J2EE user can access the components within a
J2EE application.
·
In a
commercial implementation of J2EE, for example, a J2EE user and an operating
system user might be the same, but in the J2EE SDK they are not.
J2EE Users, Realms, and
Groups
·
A J2EE
user is similar to an operating system user. Typically,
both types of users represent people. However, these two types of users are not
the same.
·
The
J2EE authentication service has no knowledge of the user and password you
provide when logging on to the operating system.
·
The
J2EE authentication service is not connected to the security mechanism of the
operating system. The two security services manage users that belong to
different realms.
·
A realm
is a collection of users that are controlled by the same authentication
policy. The J2EE authentication service governs users in two realms: certificate
and default.
·
Certificates
are used with the HTTPS protocol to authenticate Web browser clients
·
To
verify the identity of a user in the certificate realm, the authentication
service verifies a X509 certificate. The common name field of the
X509 certificate is used as the principal name.
·
In
most cases, the J2EE authentication service verifies user identity by checking
the default realm. This realm is used for the authentication of all clients except
for Web browser clients that use the HTTPS protocol and certificates.
·
A J2EE
user of the default realm may belong to J2EE group.
(A user in the certificate realm may not.)
·
A group
is a category of users, classified by common traits such as job
title or customer profile. For example, most customers of an e-commerce
application might belong to the CUSTOMER group, but the big spenders would
belong to the PREFERRED group.
·
Categorizing
users into groups makes it easier to control the access of large
numbers of users. A later section, Authorization,
discusses controlling user access to enterprise beans.
guest
.
(The password is guest123
.)
guest
,
indicating that their access in unauthenticated. guest
)
to access the application's components. guest
user. Any subsequent calls to enterprise beans are associated with the guest
user. guest
user, which is anonymous and
unauthenticated, belongs to the ANYONE role. Therefore, if you do not map
the roles, any user may invoke the methods of an enterprise bean. The
scenarios in this section show how authentication and authorization work
together to manage security for J2EE applications.
In
this scenario, an employee named Bob has moved and he wishes to update his home
address for his company's records. The company that Bob works for has a J2EE
application that allows employees to update their personal information. Figure
8-1 illustrates this application. To change his address, Bob runs a J2EE
application client that invokes the update
method in the Employee
enterprise bean.
Before Bob runs
the client, the J2EE administrator sets up the security as follows:
·
Only
the Administrator and RegularEmployee roles may invoke the update
method of the Employee
enterprise bean.
·
The
J2EE group named FullEmployee belongs to the RegularEmployee role.
·
The
J2EE user Bob belongs to the FullEmployee group in the default realm.
The
J2EE server performs the following security checks at run time:
1. When the J2EE
application client starts running it opens a dialog that prompts for the J2EE
user name and password, which Bob enters.
2.
The authentication service verifies that Bob's user name and password exist in
the default realm.
3.
Bob clicks the update button in the client, which attempts to invoke the update
method of the Employee
enterprise bean.
4.
The EJB container performs authorization. It verifies that the RegularEmployee
role, to which Bob's group (FullEmployee) belongs, has permission to invoke the
update
method.
FIGURE 8-1 Authenticated Access to an Enteprise Bean
In
the next scenario, illustrated in figure 8-2, Mary transfers money between her
savings and checking accounts from her Web browser. To transfer the funds, Mary
enters a URL that accesses a JSP component. This component calls a JavaBeansTM
component, which invokes the transfer
method of the Account
enterprise bean.
The J2EE
administrator enforces security with these rules:
·
The
JSP component is a protected resource.
·
Only
the Customer role may invoke the transfer
method of the Account
enterprise bean.
·
The
J2EE group named CurrentCustomer belongs to the Customer role.
·
Mary's
J2EE user belongs to the CurrentCustomer group in the default realm.
When
Mary transfers the funds, the J2EE server enforces security as follows:
1. Mary's browser attempts to access the JSP
component.
2. Because the component is a protected
resource, authentication is required. The Web service requests the Web browser
to prompt for the J2EE user name and password.
3. Mary enters her J2EE user name and
password, which are passed back to the J2EE server.
4. The authentication service verifies that the user
name and password exist in the default realm.
5. The Web browser is allowed to access the
JSP component.
6. Mary clicks the Transfer button on the
form generated by the JSP component, which calls a JavaBeans component.
7. The JavaBeans component attempts to
invoke the transfer
method of the Account
enterprise bean.
8. Mary's J2EE group (CurrentCustomer)
belongs to the Customer role, which is allowed to invoke the transfer
method. Therefore,
the EJB container authorizes the invocation.
FIGURE 8-2 Authenticated Access to a JSP Component and
an
·
The getCallerPrincipal
method of the EJBContext
interface returns the java.security.Principal
object that identifies the caller of the enterprise bean. (In this case, a
principal is the same as a user.) In the following example, the getUser
method of an
enterprise bean returns the name of the J2EE user that invoked it:
public String getUser() { return sessioncontext.getCallerPrincipal ().getName(); }
·
To
determine the caller of a servlet, you invoke the getUserPrincipal
method.
·
You
can determine whether an enterprise bean's caller belongs to a particular role
by invoking the isCallerInRole
method: boolean result =
context.isCallerInRole("Customer");
·
To
determine the caller's role for a servlet, you invoke the isUserInRole
method.
server.policy
. It resides in the $J2EE_HOME/lib/security
directory. client.policy
, resides in the same
directory. ·
The
EJB container maintains the pool of database connections.
·
This
pool is transparent to the enterprise beans.
·
When
an enterprise bean requests a connection, the container fetches one from the
pool and assigns it to the bean. Because the time-consuming connection has
already been made, the bean quickly gets a connection. The bean may release the
connection after each database call, since it can rapidly get another
connection.
·
And
because such a bean holds the connection for a short time, the same connection
may be shared sequentially by many beans.
·
The
persistence type of the enterprise bean determines whether or not you code the
connection routine.
·
You
must code the connection for enterprise beans that access a database and do not
have container-managed persistence. Such beans include entity beans with
bean-managed persistence and session beans.
·
For
entity beans with container-managed persistence, the Application Deployment
Tool generates the connect routines for you.
lookup
when obtaining the database
connection. This level of indirection provides several benefits: java.sql.Connection
,
that represents a session with the resource manager (DBMS). javax.sql.DataSource
object is a connection factory because it creates a java.sql.Connection
object. The
code examples in this section are from the the AccountEJB
class, which was described in the the Entity
Beans chapter. Because the AccountEJB
class uses bean-managed persistence, it connects to the database with the
following steps:
1. Specify the
logical database name.
· private String dbName = "java:comp/env/jdbc/AccountDB";
·
The java:comp/env/
prefix is
the JNDI context for the component.
·
The jdbc/AccountDB
string is
the logical database name.
2. Obtain the DataSource
associated with
the logical name.
· InitialContext ic = new InitialContext();
· DataSource ds = (DataSource) ic.lookup(dbName);
3. Get the Connection
from the DataSource
.
o Connection con = ds.getConnection();
ejbCreate
method at the beginning of a session bean's life cycle, and invokes the ejbRemove
method at the end. To retain a connection for the lifetime of a session
bean, you connect to the database in ejbCreate
and disconnect in ejbRemove
.ejbActivate
and disconnect in ejbPassivate
.
A stateful session bean requires these additional calls because the EJB
container may passivate the bean during its lifetime. During passivation,
a stateful session bean is saved in secondary storage, but a database
connection may not be saved in this manner. ejbActivate
and ejbPassivate
. setEntityContext
method. Conversely, the EJB container invokes the unsetEntityContext
method when the entity bean leaves the pooled stage and becomes eligible
for garbage collection. setEntityContext
method and disconnects in the unsetEntityContext
method.